package cn.edu.njust.alg.leetcode;

import cn.edu.njust.utils.TreeNodeUtils;

/**
 * 创建时间：2015年6月15日 上午11:47:37 项目名称：AlgorithmExercise
 * 
 * @author Zhou Xiumin
 * @version 1.0
 * @since JDK 1.7.0_21 文件名称：Leetcode_0_t.java 类说明：
 */
public class Leetcode_108_Convert_Sorted_Array_to_Binary_Search_Tree {

	public static TreeNode buildBST(int[] nums, int begin, int end) {
		if (begin > end) {
			return null;
		} else if (begin == end) {
			TreeNode root = new TreeNode(nums[begin]);
			root.left = null;
			root.right = null;
			return root;
		}
		int mid = (begin + end) / 2;
		TreeNode rootNode = new TreeNode(nums[mid]);
		rootNode.left = buildBST(nums, begin, mid - 1);
		rootNode.right = buildBST(nums, mid + 1, end);
		return rootNode;
	}

	public static TreeNode sortedArrayToBST(int[] nums) {
		if (nums == null || nums.length == 0) {
			return null;
		}
		TreeNode root = buildBST(nums, 0, nums.length - 1);
		return root;

	}

	public static void main(String[] args) {
		int[] nums = { 1, 2, 3, 4, 5, 6, 7 };
		TreeNode root = sortedArrayToBST(nums);
		TreeNodeUtils.printList(root);
	}

}
